package fun.coding.jeffreys.judge;

import java.util.ArrayList;
import java.util.List;

public class NestedListWeightedSum {
	public static void main(String[] args) {
		// {2, {4}}
		NestedList n1 = new NestedListImpl(2);
		List<NestedList> l = new ArrayList<NestedList>();
		l.add(new NestedListImpl(4));
		NestedList n2 = new NestedListImpl(l);
		
		List<NestedList> test1 = new ArrayList<NestedList>();
		test1.add(n1);
		test1.add(n2);
		
		// null
		List<NestedList> test2 = null;
		// empty
		List<NestedList> test3 = new ArrayList<NestedList>();
		
		// {{{2}}}
		NestedList a1 = new NestedListImpl(2);
		List<NestedList> a1l = new ArrayList<NestedList>();
		a1l.add(a1);
		
		List<NestedList> a2l = new ArrayList<NestedList>();
		NestedList a2 = new NestedListImpl(a1l);
		a2l.add(a2);
		
		List<NestedList> test4 = new ArrayList<NestedList>();
		NestedList a3 = new NestedListImpl(a2l);
		test4.add(a3);
		
		// {1, {{2}}}
		List<NestedList> test5 = new ArrayList<NestedList>();
		test5.add(a3);
		NestedList b1 = new NestedListImpl(1);
		test5.add(b1);
		
		
		NestedListWeightedSum instance = new NestedListWeightedSum();
		assert instance.weightedSum(test1) == 10;
		assert instance.weightedSum(test2) == 0;
		assert instance.weightedSum(test3) == 0;
		assert instance.weightedSum(test4) == 6;
		assert instance.weightedSum(test5) == 7;
	}
	
	
	/**
	 * Given a nested list of integers, returns the sum of all integers in the list weighted by their depth
	 * {1} -> 1
	 * {2,{4}} -> 2*1 + 4*2 = 10
	 * {1, {2}, 3, {4, {1}} = 1*1 + 2*2 + 3*1 + 4*2 + 1*3 = 16 
	 * @param list
	 * @return
	 */
	public int weightedSum(List<NestedList> list) {
		return helper(list, 1);
	}
	
	private int helper(List<NestedList> list, int weight) {
		if (list == null || list.size() == 0) return 0;
		
		int sum = 0;
		for (NestedList n : list) {
			if (n.isInt()) {
				sum += n.getInt() * weight;
			} else {
				sum += helper(n.getList(), weight + 1);
			}
		}
		return sum;
	}

}
